STOMP通过WebSocket为angular2服务可与:angular4和ionic3兼容
1.下载插件
分别执行以下指令npm install stompjs --save
npm install sockjs-client --save
npm install ng2-stomp-service --save
2.添加stompjs和sockjs-client模块声明
在 - > typings.d.ts中添加declare module 'stompjs';
declare module 'sockjs-client';
3.配置 angular-cli.json
使用angular-cli 创建的项目,那么在 - > angular-cli.json中添加以下代码,目的引入js(如果不是,我也不知道)"../node_modules/sockjs-client/dist/sockjs.min.js",
"../node_modules/stompjs/lib/stomp.js"
4.配置 tsconfig.json
在compilerOptions的同级下添加"include": [
"src/**/*",
"node_modules/ng2-stomp-service/dist/stomp.service.ts"
]
5.在app.module.ts中声明stompService
{provide:'stompService',useClass:StompService} |
6.使用(以上准备好后开始使用吧)
SleepmonitorComponent.ts
import {Component, Inject, OnDestroy, OnInit} from '@angular/core'; |
7.后台代码
接收处理Action中"/test", method = RequestMethod.POST)// 此行应该可以省略 (value =
"/test") (
public void test(@RequestBody UserDevice userDevice) {
try {
LOGGER.info("你的业务逻辑");
} catch (Exception e) {
LOGGER.error("websocket处理异常:【{}】", e.getMessage());
}
}
8.服务器端配置
SpringMVC配置类WebSocketConfig.classpackage iguard.websocket.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
// 激活Websocket消息代理
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
public void configureMessageBroker(MessageBrokerRegistry config) {
// 代理目的地以/chat、/doctor为前缀,客户端订阅消息的前缀
config.enableSimpleBroker("/sleep", "/user");
// 应用程序以/app为前缀,客户端发送消息的前缀
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 指向websocket连接的地址
registry.addEndpoint("/test").setAllowedOrigins("*").withSockJS();
}
}